//
//  NoticeBoardVC.m
//  sensen_ios
//
//  Created by pro on 16/1/30.
//  Copyright © 2016年 pro. All rights reserved.
//

#import "NoticeBoardVC.h"
//视图
#import "NoticeRewardCell.h"
#import "NoticeCell.h"
//模型
#import "NoticeModel.h"//公告model
#import "LotteryModel.h"//评奖model
//控制器
#import "WebViewController.h"//页面跳转
#import "PostReplyModel.h"
@interface NoticeBoardVC ()<UITableViewDataSource,UITableViewDelegate>{
    NSInteger _page_no;//页码,默认0
    NSInteger _pageSize;//每页显示个数，默认10,最大30,最小1,
    
}
//视图
@property (nonatomic,strong)UITableView *tableView;//视图
@property (nonatomic,strong)UILabel *emptyView;//空视图
//数组
@property (nonatomic,strong)NSMutableArray *noticeArray;//存放公告数组
@property (nonatomic,strong)NSMutableArray *lotteryAry;//抽奖数组
@property (nonatomic,strong)NSMutableArray *awardAry;//评奖
//菊花
@property (strong, nonatomic) UIActivityIndicatorView *activityIndicator ;

@end
@implementation NoticeBoardVC
static int  flag = 0;//用来判断请求次数
- (void)viewDidLoad {
    [super viewDidLoad];
    self.title = @"公告栏";
    self.view.backgroundColor = [UIColor whiteColor];
    [self _initTableView];
    _activityIndicator = [[UIActivityIndicatorView alloc] initWithFrame:CGRectMake(0, 0, 50, 50)];
    _activityIndicator.center = self.tableView.center;
    [self.view addSubview:_activityIndicator];
    self.activityIndicator.activityIndicatorViewStyle = UIActivityIndicatorViewStyleGray;
    [self.activityIndicator startAnimating];
    
}
- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:YES];
    MainTabBarController *main = (MainTabBarController *)self.tabBarController;
    [main showTabBar];
    [self _initData];
    // 设置导航栏颜色
    [self.navigationController.navigationBar setBackgroundImage:[UIImage imageWithColor:SS_NAVI_ORANGE_COLOR] forBarMetrics:UIBarMetricsDefault];
    
}

#pragma mark----创建视图
//初始化Tableview
- (void)_initTableView {
//    _tableView = [[UITableView alloc] initWithFrame: ];
    _tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT - 64) style:UITableViewStyleGrouped];
      _tableView.delegate = self;
    _tableView.dataSource = self;
    _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    _tableView.showsVerticalScrollIndicator = NO;
    [_tableView setBackgroundColor:Gray_COLOR];
    [self.view addSubview:_tableView];
    _tableView.hidden = YES;
    _tableView.tableFooterView = [[UIView alloc] init];
    
}
// 没有信息时候的视图
- (void)_createEmptyViewView {
    //      [SVProgressHUD dismiss];
    CGFloat x = 0;
    CGFloat y = 0;
    CGFloat width = 100;
    CGFloat height = 20;
    _emptyView = [[UILabel alloc] initWithFrame:CGRectMake(x, y, width, height)];
    _emptyView.font = FONT(15);
    _emptyView.text = @"暂无公告";
    _emptyView.textColor = [UIColor darkGrayColor];
    _emptyView.textAlignment = NSTextAlignmentCenter;
    [self.view addSubview:_emptyView];
    _emptyView.center = self.tableView.center;
    _emptyView.hidden = YES;
    if (flag == 2&&_noticeArray.count == 0&&_awardAry.count == 0) {
        [_activityIndicator stopAnimating];
        _emptyView.hidden = NO;
        _tableView.hidden = YES;
        
    }else if(flag == 2){
        [_activityIndicator stopAnimating];
        _emptyView.hidden = YES;
        _tableView.hidden = NO;
    }
    
}
#pragma mark--获取数据
- (void)_initData{
    //获取抽奖数据
    NSMutableDictionary *params1 = [NSMutableDictionary dictionary];
    [params1 setValue:@"6058" forKey:@"position"];
    [BoyeHttpClient post:@"BY_News_query" apiVerson:100 params:params1 success:^(AFHTTPRequestOperation *operation, id result) {
        NSLog(@"%@",result);
        flag += 1;
        _lotteryAry = [NSMutableArray array];
        if ([result isKindOfClass:[NSDictionary class]] &&  ![result[@"list"] isKindOfClass:[NSNull class]] ) {
            for (NSDictionary *dic in result[@"list"]) {
                LotteryModel *model = [[LotteryModel alloc] initContentWithDic:dic];
                [_lotteryAry addObject:model];
            }
        }
        [self _createEmptyViewView];
        [_tableView reloadData];
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        NSLog(@"%@",error);
    }];
    
    //获取评奖结果
    NSMutableDictionary *params2 = [NSMutableDictionary dictionary];
    [params2 setValue:@"6059" forKey
                     :@"position"];
    [BoyeHttpClient post:@"BY_News_query" apiVerson:100 params:params2 success:^(AFHTTPRequestOperation *operation, id result) {
        NSLog(@"%@",result);
        flag += 1;
        _awardAry = [NSMutableArray array];
        if (![result[@"list"] isKindOfClass:[NSNull class]]) {
            for (NSDictionary *dic in result[@"list"]) {
                LotteryModel *model = [[LotteryModel alloc] initContentWithDic:dic];
                [_awardAry addObject:model];
            }
        }
        [self _createEmptyViewView];
        [_tableView reloadData];
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        NSLog(@"%@",error);
    }];
    //获取公告栏的数据
    _page_no = 1;
    _pageSize = 10;
    NSMutableDictionary *params = [NSMutableDictionary dictionary];
    [params setValue:@"6054" forKey:@"position"];
    [params setValue:[NSString stringWithFormat:@"%ld",(long)_page_no] forKey:@"page_no"];
    [params setValue:[NSString stringWithFormat:@"%ld",(long)_pageSize] forKey:@"page_size"];
    [BoyeHttpClient post:@"BY_News_query" apiVerson:101 params:params success:^(AFHTTPRequestOperation *operation, id result) {
        //        NSLog(@"%@",result);
        flag += 1;
        _noticeArray = [NSMutableArray array];
        
        if (![result[@"list"] isKindOfClass:[NSNull class]]) { // 有数据
            for (NSDictionary *dic in result[@"list"]) {
                NoticeModel *noticeModel = [[NoticeModel alloc] initContentWithDic:dic];
                [_noticeArray addObject:noticeModel];
            }
            // 下拉加载更多
            MJRefreshAutoNormalFooter *footer = [MJRefreshAutoNormalFooter footerWithRefreshingTarget:self refreshingAction:@selector(_getMoreData)];
            _tableView.footer = footer;
        }
        [self _createEmptyViewView];
        [_tableView reloadData];
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        
    }];
}
#pragma mark--加载更多
- (void)_getMoreData {
    _page_no += 1; // 请求更多数据，page自增1
    NSMutableDictionary *params = [NSMutableDictionary dictionary];
    [params setValue:@"6054" forKey:@"position"];
    [params setObject:@(_page_no) forKey:@"page_no"];
    [params setObject:@(_pageSize) forKey:@"page_size"];
    [BoyeHttpClient post:@"BY_News_query" apiVerson:100 params:params success:^(AFHTTPRequestOperation *operation, id result) {
        
        NSString *countStr = result[@"count"];
        int count = [countStr intValue];
        if (![result[@"list"] isKindOfClass:[NSNull class]]) { // 有数据
            for (NSDictionary *dic in result[@"list"]) {
                NoticeModel *noticeModel = [[NoticeModel alloc] initContentWithDic:dic];
                [_noticeArray addObject:noticeModel];
            }
        }
        if (_noticeArray.count == count) {
            [_tableView.footer noticeNoMoreData];
        }
        [_tableView reloadData];
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        NSLog(@"%@",error);
        [_tableView.footer endRefreshing];
    }];
}
#pragma mark-----UITableViewDataSource
//返回行数
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    if (section == 0) {
        if (_awardAry.count != 0) {
            return  _lotteryAry.count +1;
        }
        return  _lotteryAry.count;
    }else
        return _noticeArray.count;
}
//返回组数
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 2;
}
//返回cell
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    if (indexPath.section == 0) {
        NoticeRewardCell *cell = [self.tableView dequeueReusableCellWithIdentifier:@"RewardCell"];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        if (cell == nil) {
            cell = [[NSBundle mainBundle] loadNibNamed:@"NoticeRewardCell" owner:nil options:nil].lastObject;
        }
        if (indexPath.row == 0) {
            LotteryModel *model = self.lotteryAry[indexPath.row];
            cell.lotteryModel = model;
            return cell;
        }else{
            LotteryModel *model = self.awardAry[0];
            cell.lotteryModel = model;
            return cell;}
    }else{
        static NSString *indentifer = @"cell";
        NoticeCell *cell = [NoticeCell getNoticeCellWith:tableView indentifer:indentifer];
        NoticeModel *model = self.noticeArray[indexPath.row];
        cell.noticeModel = model;
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        return cell;
    }
}
#pragma mark----UITableViewDelegate
//返回行高
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    if (indexPath.section == 0) {
        return SCREEN_WIDTH / 1.8;
    }else
        return 63;
}
//返回组头高
-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    if (section == 1) {
        return 22;
    }else
        return 1;
}
//返回组头视图
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    if (section == 1) {
        if (_noticeArray.count == 0||_noticeArray == nil) {
            return nil;
        }else{
            UIView *view = [[NSBundle mainBundle] loadNibNamed:@"HeaderView" owner:nil options:nil].lastObject;
            return view;
        }
    }else
        return nil;
}
- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section{
    return nil;
}
//点击单元格事件
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    UserModel *user = [CommonCache getUserInfo];
    if (!user.uid) {
        LoginVC *vc = [[LoginVC alloc] init];
        BaseNavVC *naVC = [[BaseNavVC alloc] initWithRootViewController:vc];
        [self presentViewController:naVC animated:YES completion:nil];
        return;
    }
    if (indexPath.section == 0) {
        if(indexPath.row == 0){
            [self jumpWebView:[NSString stringWithFormat:@"%@/Game/index?uid=%@&psw=%@",WEB_BASE_URL,user.uid,user.password] and:@"幸运抽奖"];
        }else{
            LotteryModel *model = _awardAry[0];
            if (![model.jump_url isStringNull]) {
                [self jumpWebView:model.jump_url and:@"评奖结果"];
            }else{
         
                //                [self jumpWebView:@"http://sunsun.itboye.com/index.php/Webview/Post/viewLottery?from=app" and:@"评奖结果"];
                PostReplyModel *model2 = [[PostReplyModel alloc] init];
                model2.fid = model.lottery_id;
                model2.post_title = model.post_title;
                model2.main_img = model.main_img;
                model2.post_excerpt  = model.post_title;
                
                WebVC *webVC = [[WebVC alloc] initWithUrlString:[NSString stringWithFormat:@"Post/viewPost?id=%@&from=app",model.lottery_id]];
                webVC.titleString = @"评奖结果";
                webVC.model = model2;
                //[webVC createRightBarButtonItemWithImagename:@"论坛首页_详情页_分享"];
                [self.navigationController pushViewController:webVC animated:YES];

            }
        }
    }else{
        NoticeModel *model = self.noticeArray[indexPath.row];
        if (![model.jump_url isStringNull]) {
            [self jumpWebView:model.jump_url and:@"公告"];
        }else{
            
            PostReplyModel *model2 = [[PostReplyModel alloc] init];
            model2.fid = model.notice_id;
            model2.post_title = model.post_title;
            model2.main_img = model.main_img;
            model2.post_excerpt  = model.post_title;
            
            WebVC *webVC = [[WebVC alloc] initWithUrlString:[NSString stringWithFormat:@"Post/viewPost?id=%@&from=app",model.notice_id]];
            webVC.titleString = @"公告";
            webVC.model = model2;
            //[webVC createRightBarButtonItemWithImagename:@"论坛首页_详情页_分享"];
            [self.navigationController pushViewController:webVC animated:YES];
        }
    }
}
#pragma mark --跳转网页
- (void)jumpWebView:(NSString *) url  and:(NSString *) titleStr{
    WebViewController *webVC = [[WebViewController alloc] initWithUrlString:url];
    webVC.titleString = titleStr;
    [self.navigationController pushViewController:webVC animated:YES];
}

@end
